ctypeslib 2.0 Introduction

Hi you,

So here we are going to show a small demo of ctypeslib 2.0.

The purpose of ctypeslib is to transform C headers into ABI-compatible python code using ctypes.

First, lets start with a few easy C headers that we want to "convert" to python ctypes code.


In [1]:
c_headers = '''
/** very simple tests */
int version = 2;
char text[] = "Hello World!";
int minors[] = {2,0,0};
'''

we now can use the ctypeslib parser.

Note: the ctypeslib python library require the LLVM Clang library and its python bindings.


In [2]:
import ctypeslib
from ctypeslib.codegen import clangparser
# let's create a parser
parser = clangparser.Clang_Parser(flags=[])
# parse the c headers
parser.parse_string(c_headers)
# get the result
items = parser.get_result()
print items


[Variable(comment=None,init=Hello World!,typ=ArrayType(...),name=text,location=('/tmp/tmpZrixvs.h', 4)), Variable(comment=very simple tests,init=2,typ=FundamentalType(...),name=version,location=('/tmp/tmpZrixvs.h', 3)), Variable(comment=None,init=[2, 0, 0],typ=ArrayType(...),name=minors,location=('/tmp/tmpZrixvs.h', 5))]

Now, we have parsed the C headers.

The parser returns an collection of intermediate python objects.

We want to produce a python source code out of it. Let's use the codegenerator.


In [3]:
# we need a output stream to store the generated code 
from StringIO import StringIO
output = StringIO()

from ctypeslib.codegen import codegenerator
# get the generator 
gen = codegenerator.Generator(output)
# and produce the code
gen.generate(parser, items)

The code is generated in the output stream (which could be a file)


In [4]:
print output.getvalue()


# -*- coding: utf-8 -*-
#
# TARGET arch is: []
# WORD_SIZE is: 8
# POINTER_SIZE is: 8
# LONGDOUBLE_SIZE is: 16
#
import ctypes




version = 2 # Variable ctypes.c_int32
text = 'Hello World!' # Variable ctypes.c_char * 12
minors = [2, 0, 0] # Variable ctypes.c_int32 * 3
__all__ = ['text', 'version', 'minors']

Let's try to load that code in the python console


In [5]:
# -*- coding: utf-8 -*-
#
# TARGET arch is: []
# WORD_SIZE is: 8
# POINTER_SIZE is: 8
# LONGDOUBLE_SIZE is: 16
#
import ctypes




version = 2 # Variable ctypes.c_int32
text = 'Hello World!' # Variable ctypes.c_char * 12
minors = [2, 0, 0] # Variable ctypes.c_int32 * 3
__all__ = ['text', 'version', 'minors']

Are the C variables now accessible in Python ?


In [6]:
print text
print 'Brought to you by ctypeslib version', version
print minors


Hello World!
Brought to you by ctypeslib version 2
[2, 0, 0]

Success !!